<template>
  <el-container class="advance-query-form form-dict-management">
    <el-aside width="300px">
      <el-card class="base-card" shadow="never" :body-style="{ padding: '0px' }" style="border: none;">
        <div slot="header" class="base-card-header">
          <el-row type="flex" justify="space-between" align="middle" style="width: 100%;">
            <span>字典列表</span>
            <div>
              <el-radio-group v-model="dictType" size="mini" @change="onDictTypeChange">
                <el-radio-button label="table">字典表字典</el-radio-button>
                <el-radio-button label="code">编码字典</el-radio-button>
              </el-radio-group>
              <el-button type="text" title="新建编码字典"
                :disabled="dictType !== 'code'"
                icon="el-icon-circle-plus-outline"
                style="margin-left: 10px;"
                @click="onEditGlobalDict()"
              />
            </div>
          </el-row>
        </div>
        <el-scrollbar :style="{'height': (getMainContextHeight - 51) + 'px'}" class="custom-scroll">
          <el-tree ref="dictList" :data="currentDictList" :props="{label: 'name'}"
            node-key="keyName" :highlight-current="true"
            :current-node-key="(currentDict || {}).variableName" @node-click="onDictChange"
          >
            <div class="module-node-item" slot-scope="{ data }">
              <el-row type="flex" justify="space-between" align="middle" style="margin-right: 15px;">
                <div>
                  <span style="padding-left: 24px;">{{data.name}}</span>
                  <el-tag v-if="data.tenantCommon" size="mini" type="success" style="margin-left: 10px;" effect="dark">公共字典</el-tag>
                </div>
                <div v-if="dictType === 'code'">
                  <el-button type="text" :size="defaultFormItemSize" icon="el-icon-edit-outline"
                    @click.stop="onEditGlobalDict(data)"
                  />
                  <el-button type="text" :size="defaultFormItemSize" icon="el-icon-delete"
                    @click.stop="onDeleteGlobalDict(data)"
                  />
                </div>
              </el-row>
            </div>
          </el-tree>
        </el-scrollbar>
      </el-card>
    </el-aside>
    <el-main style="margin-left: 15px; background-color: white; padding: 20px;">
      <el-form label-width="120px" :size="defaultFormItemSize" label-position="left" @submit.native.prevent>
        <filter-box :item-width="350">
          <el-form-item v-if="dirtyCount > 0" label="失效缓存数量：">
            <span style="color: #F56C6C;">{{dirtyCount}}</span>
          </el-form-item>
          <el-button slot="operator" type="primary" :size="defaultFormItemSize" :plain="true"
            :disabled="!checkPermCodeExist('formSysDict:fragmentSysDict:reloadCache') || currentDict == null"
            @click="onRefreshCacheData">
            同步缓存
          </el-button>
          <el-button slot="operator" type="primary" :size="defaultFormItemSize"
            v-show="currentDict && !currentDict.tenantCommon"
            :disabled="!checkPermCodeExist('formSysDict:fragmentSysDict:add') || currentDict == null"
            @click="onAddDictData">
            添加数据
          </el-button>
        </filter-box>
      </el-form>
      <el-row>
        <el-col :span="24">
          <el-table border :data="getCurrentDictData" :size="defaultFormItemSize" header-cell-class-name="table-header-gray"
            :row-style="tableRowStyle"
            :height="(getMainContextHeight - 90) + 'px'" row-key="id">
            <el-table-column label="ID">
              <template slot-scope="scope">
                <span>{{scope.row.itemId || scope.row.id}}</span>
              </template>
            </el-table-column>
            <el-table-column label="字典名称" prop="name">
              <template slot-scope="scope">
                <span>{{scope.row.name}}</span>
                <el-tag v-if="scope.row.dirty" :size="defaultFormItemSize" effect="dark" type="warning"
                  style="margin-left: 15px;">
                  缓存失效
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="启用" v-if="dictType === 'code'">
              <template slot-scope="scope">
                <el-switch size="mini" v-model="scope.row.status"
                  :active-value="0" :inactive-value="1"
                  :disabled="currentDict && currentDict.tenantCommon"
                  @change="onDictDataStatusChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150px" v-if="currentDict && !currentDict.tenantCommon">
              <template slot-scope="scope">
                <el-button type="text" :size="defaultFormItemSize" :disabled="!checkPermCodeExist('formSysDict:fragmentSysDict:update')" @click="onUpdateDictDataClick(scope.row)">编辑</el-button>
                <el-button type="text" :size="defaultFormItemSize" :disabled="!checkPermCodeExist('formSysDict:fragmentSysDict:delete')" @click="onDeleteDictDataClick(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script>
import { mapGetters } from 'vuex';
import { treeDataTranslate } from '@/utils';
/* eslint-disable-next-line */
import { DictionaryController, SysGlobalDictController } from '@/api';
import editDictData from '@/views/upms/formEditDictData';
import editGlobalDict from '@/views/upms/formEditGlobalDict';

export default {
  name: 'formDictManagement',
  data () {
    return {
      // 字典表字典
      dictList: [
      ],
      // 全局编码字典
      globalDictList: [],
      dictType: 'table',
      dirtyCount: 0,
      currentDict: undefined,
      currentDictDataList: []
    }
  },
  methods: {
    // 切换编码字典数据启用状态
    onDictDataStatusChange (row) {
      SysGlobalDictController.updateItemStatus(this, {
        id: row.id,
        status: row.status
      }).then(res => {
        this.updateDictData();
      }).catch(e => {});
    },
    // 字典类型切换
    onDictTypeChange () {
      setTimeout(() => {
        this.onDictChange(this.currentDictList[0]);
      }, 30);
    },
    // 编辑、新建编码字典
    onEditGlobalDict (row) {
      this.$dialog.show(row ? '编辑编码字典' : '新建编码字典', editGlobalDict, {
        area: ['600px']
      }, {
        rowData: row
      }).then(res => {
        this.loadGlobalDictList().catch(e => {});
      }).catch(e => {});
    },
    // 删除编码字典
    onDeleteGlobalDict (row) {
      let params = {
        dictId: row.dictId
      };

      this.$confirm('是否删除此编码字典？').then(res => {
        return SysGlobalDictController.delete(this, params);
      }).then(res => {
        this.$message.success('删除成功');
        this.loadGlobalDictList().catch(e => {});
      }).catch(e => {});
    },
    tableRowStyle ({row, rowIndex}) {
      if (row.dirty) {
        return {
          background: '#FFE1E1'
        }
      }
    },
    // 获取字典数据
    updateDictData () {
      this.currentDictDataList = [];
      this.dirtyCount = 0;
      if (this.currentDict && this.currentDict.listApi) {
        this.currentDict.listApi(this, {
          dictCode: this.currentDict.dictCode
        }).then(res => {
          let cachedMap = new Map();
          if (Array.isArray(res.cachedResultList)) {
            res.cachedResultList.forEach(item => {
              cachedMap.set(item.id, item);
            });
          }
          if (Array.isArray(res.fullResultList)) {
            res.fullResultList.forEach(item => {
              let cachedItem = cachedMap.get(item.id);
              if (cachedItem == null || cachedItem.name !== item.name) {
                item.dirty = true;
                this.dirtyCount++;
              }
            });
          }
          cachedMap = null;
          if (this.currentDict.treeFlag) {
            this.currentDictDataList = treeDataTranslate(res.fullResultList, 'id', 'parentId');
          } else {
            this.currentDictDataList = res.fullResultList;
          }
        }).catch(e => {});
      }
    },
    // 选中字典切换
    onDictChange (data) {
      if (this.currentDict === data) return;
      this.currentDictDataList = [];
      this.currentDict = data;
      if (this.currentDict != null) {
        this.$nextTick(() => {
          this.$refs.dictList.setCurrentKey(this.currentDict.keyName);
        });
        this.updateDictData();
      }
    },
    onRefreshCacheData () {
      this.$confirm('是否同步缓存？').then(res => {
        return this.currentDict.reloadCachedDataApi(this, {
          dictCode: this.currentDict.dictCode
        });
      }).then(res => {
        this.$message.success('同步成功');
        this.updateDictData();
      }).catch(e => {});
    },
    onAddDictData () {
      this.$dialog.show(`新建字典数据 - [${this.currentDict.name}]`, editDictData, {
        area: '500px'
      }, {
        dictInfo: this.currentDict,
        dictData: this.currentDict.treeFlag ? this.currentDictDataList : []
      }).then(res => {
        this.updateDictData();
      }).catch(e => {});
    },
    onUpdateDictDataClick (row) {
      this.$dialog.show(`编辑字典数据 - [${this.currentDict.name}]`, editDictData, {
        area: '500px'
      }, {
        dictInfo: this.currentDict,
        currentData: row,
        dictData: this.currentDict.treeFlag ? this.currentDictDataList : []
      }).then(res => {
        this.updateDictData();
      }).catch(e => {});
    },
    onDeleteDictDataClick (row) {
      this.$confirm('是否删除此字典数据？').then(res => {
        let params = {};
        if (this.dictType === 'code') {
          params.dictCode = this.currentDict.dictCode;
          params.id = row.id;
        } else {
          params[this.currentDict.idKey] = row.id;
        }
        return this.currentDict.deleteApi(this, params);
      }).then(res => {
        this.$message.success('删除成功');
        this.updateDictData();
      }).catch(e => {});
    },
    // 获取编码字典列表
    loadGlobalDictList () {
      return new Promise((resolve, reject) => {
        SysGlobalDictController.list(this, {}).then(res => {
          let currentDict = null; // 当前选中字典
          this.globalDictList = (res.data.dataList || []).map(item => {
            let temp = {
              ...item,
              keyName: item.dictCode,
              variableName: 'globalDictItem',
              dictCode: item.dictCode,
              name: item.dictName,
              nameKey: 'itemName',
              idKey: 'itemId',
              deletedKey: 'itemIds',
              parentKey: '',
              treeFlag: false,
              listApi: SysGlobalDictController.listAll,
              addApi: SysGlobalDictController.addItem,
              deleteApi: SysGlobalDictController.deleteItem,
              updateApi: SysGlobalDictController.updateItem,
              reloadCachedDataApi: SysGlobalDictController.reloadCachedData
            }
            if (temp.dictCode === (this.currentDict || {}).dictCode) {
              currentDict = temp;
            }
            return temp;
          });
          // 默认选中第一个字典
          if (currentDict == null) currentDict = this.globalDictList[0];
          if (currentDict != null && this.dictType === 'code') {
            this.onDictChange(currentDict);
          }
          resolve();
        }).catch(e => {
          reject(e);
        })
      });
    }
  },
  computed: {
    getCurrentDictData () {
      return this.currentDictDataList;
    },
    currentDictList () {
      return this.dictType === 'table' ? this.dictList : this.globalDictList;
    },
    ...mapGetters(['getMainContextHeight'])
  },
  mounted () {
    this.loadGlobalDictList().then(res => {
      this.onDictChange(this.currentDictList[0]);
    }).catch(e => {});
  }
}
</script>

<style scoped>
  .form-dict-management >>> .el-tree-node__content {
    height: 35px;
  }

  .form-dict-management >>> .el-tree-node__content .is-leaf {
    display: none;
  }

  .module-node-item {
    width: 100%;
    height: 35px;
    line-height: 35px;
  }
</style>
